package net.goodapp.service;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import net.goodapp.dao.DatabaseDAO;
import net.goodapp.model.ColumnInfo;
import net.goodapp.model.TableInfo;
import net.goodapp.util.NamingConventions;

public class DatabaseService {
	private static final Log logger = LogFactory.getLog(DatabaseDAO.class);
	Properties javaDataTypeProperties=new Properties();
	private DatabaseDAO databaseDAO;
	
	public DatabaseService() throws IOException {
		//InputStream inputStream=this.getClass().getClassLoader().getResourceAsStream("javaDataType.properties");
		//logger.info("InputStream is null?"+inputStream==null?"true":"false");
		//javaDataTypeProperties.load(inputStream);
		javaDataTypeProperties.load(this.getClass().getClassLoader().getResourceAsStream("javaDataType.properties"));
		
		logger.info("Load java data type mapping from javaDataType.properties.");
	}
	
	public DatabaseDAO getDatabaseDAO() {
		return databaseDAO;
	}
	public void setDatabaseDAO(DatabaseDAO databaseDAO) {
		this.databaseDAO = databaseDAO;
	}
	/**
	 * 获取指定数据库的下所有表及表中列集合的信息
	 * @return 返回包含了表、列、主键及列字段类型和大小的信息的集合
	 * @throws SQLException
	 * @throws IOException
	 */
	public List<TableInfo> getTableInfos() throws SQLException,IOException {
		List<TableInfo> tableInfos=databaseDAO.getTableInfos();
		String jdbcType=null;
		String primaryKeyName=null;
		for (TableInfo tableInfo : tableInfos) {
			tableInfo.setEntityName(NamingConventions.tableNameToClassName(tableInfo.getTableName()));
			if(tableInfo.getPrimaryKeyInfos()!=null&&tableInfo.getPrimaryKeyInfos().size()==1){
				primaryKeyName=tableInfo.getPrimaryKeyInfos().get(0).getColumnName();
				logger.info("Table ["+tableInfo.getTableName()+"] primary key is ["+ primaryKeyName+ "].");
			}
			for (ColumnInfo columnInfo : tableInfo.getColumnInfos()) {
				columnInfo.setPropertyName(NamingConventions.fieldToProperty(columnInfo.getColumnName()));
				jdbcType=javaDataTypeProperties.getProperty(""+columnInfo.getSqlType());
				columnInfo.setJavaType(jdbcType);
				if(columnInfo.getColumnName().equalsIgnoreCase(primaryKeyName)){
					tableInfo.setPrimaryKeyColumnName(columnInfo.getColumnName());
					tableInfo.setPrimaryKeyName(NamingConventions.fieldToProperty(primaryKeyName));
					jdbcType=javaDataTypeProperties.getProperty(""+columnInfo.getSqlType());
					tableInfo.setPrimaryKeyType(jdbcType);
					logger.info("Table ["+tableInfo.getTableName()+"] primary key name is ["+ primaryKeyName+ "] and type is "+jdbcType);
				}
			}
		}
		
		return tableInfos;
	}
}
